﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace MailServer {
    public partial class FServer : Form {
        private Server.Server server;

        public FServer() {
            InitializeComponent();
        }

        private void CargarDatos() {
            server = new Server.Server(txRuta.Text);
            foreach(string u in server.ListUser()) {
                lbU.Items.Add(u);
            }
            btAddU.Enabled = true;
            btEditU.Enabled = true;
            btDelU.Enabled = true;
            btGuardar.Enabled = true;
        }

        private bool ExisteUsuario(string usuario) {
            for(int i = 0; i < lbU.Items.Count; i++)
                if(lbU.Items[i].ToString() == usuario)
                    return true;
            return false;
        }

        private void btRuta_Click(object sender, EventArgs e) {
            if(od1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                txRuta.Text = od1.FileName;
                CargarDatos();
            }
        }

        private void btAddU_Click(object sender, EventArgs e) {
            string u = Microsoft.VisualBasic.Interaction.InputBox("Nombre del nuevo usuario", "Agregar usuario", "");
            if(!string.IsNullOrEmpty(u) && !ExisteUsuario(u)) {
                lbU.Items.Add(u);
                server.CreateUser(u);
            } else {
                MessageBox.Show("Usuario no válido", "Servidor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btEditU_Click(object sender, EventArgs e) {
            int i = lbU.SelectedIndex;
            if(i > -1) {
                string uA = lbU.Items[i].ToString();
                string u = Microsoft.VisualBasic.Interaction.InputBox("Nuevo nombre del usuario", "Modificar usuario", lbU.Items[i].ToString());
                if(!string.IsNullOrEmpty(u) && !ExisteUsuario(u)) {
                    lbU.Items[i] = u;
                    server.RemoveUser(uA);
                    server.CreateUser(u);
                }
            }
        }

        private void btDelU_Click(object sender, EventArgs e) {
            int i = lbU.SelectedIndex;
            if(i > -1 && MessageBox.Show("¿Eliminar el usuario?", "Eliminar usuario", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK) {
                server.RemoveUser(lbU.Items[i].ToString());
                lbU.Items.RemoveAt(i);
            }
        }

        private void btGuardar_Click(object sender, EventArgs e) {

        }

        private void btCerrar_Click(object sender, EventArgs e) {
            Close();
        }
    }
}
